package network;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class FileDownloadServer extends JFrame implements Runnable{
	static int staticPort = 5000;
	MultiChatServerThread serverThread;
	MultiChatServer server;
	ObjectOutputStream send;
	String ip;
	ServerSocket serverSocket;
	String folder = "/downTemp/";
	String oriFileName;
	
	private JPanel contentPane;
	private JButton btnNewButton;
	private JScrollPane scrollPane;
	private JTextArea result;


	/**
	 * Create the frame.
	 */
	public FileDownloadServer(MultiChatServerThread st, MultiChatServer s, ObjectOutputStream send) {
		this.serverThread = st;
		this.server = s;
		this.send = send;
		
		setTitle("File Server");
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		contentPane.add(getBtnNewButton());
		contentPane.add(getScrollPane());
		// 만약 /download 폴더가 없으면 서버에 생성
		try{
			
			InetAddress ia = InetAddress.getLocalHost();
			ip = ia.getHostAddress();
			
			folder += staticPort + "/";
			File f = new File(folder);
			if(! f.exists()) f.mkdirs();
		
			
		}catch(Exception ex){
			
		}
		
	}

	@Override
	public void run() {
		try{
			result.append("파일 수신 서버가 시작되었습니다.\n");
			serverSocket = new ServerSocket(staticPort);
			
			
			// 클라이언트에게 서버의 아이피와 포트번호전송
			String msg = ip + "," + staticPort;
			SocketData sd = new SocketData("fileTransPort", "server", null,msg);
			send.writeObject(sd);
			send.flush();
			
			staticPort += 5;
			
			result.append("파일을 전송할 클라이언트 접속대기 중...\n");
			Socket socket = serverSocket.accept();
			
			result.append("파일을 전송할 클라이언트 접속됩...\n");
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			
			String fileName = dis.readUTF();
			result.append("수신된 파일명은 " + fileName + " 입니다.\n");
			int pos = fileName.lastIndexOf("\\");
			oriFileName = fileName.substring(pos+1);
			
			result.append("저장될 파일명은 " + folder+ oriFileName + " 입니다.\n");
			FileOutputStream fos = new FileOutputStream(folder+oriFileName);
			
			
			byte[] d = new byte[1024];
			int len=0;
			result.append("파일이 수신되고 있습니다..\n");
			while( (len = dis.read(d)) != -1 && socket.isConnected()){
				fos.write(d, 0, len);
			}
			result.append("파일이 모두 수신되었습니다...\n");
			result.append("접속된 모든 유저에게 배포하도록 메시지를 전송합니다..\n");
			
			connectFileUploadServer();
			
			fos.close();
			dis.close();
			socket.close();
			this.dispose();
			
		}catch(Exception ex){
			result.append("파일을 전송중인 클라이언트의 접속이 끊어졌습니다.\n");
		}
		
	}
	
	// 모든 유저에게 FileUpload 서버에 접속하도록 메시지 전달.
	public void connectFileUploadServer() throws Exception{

		Collection<String> c = server.clients.keySet();
		Iterator<String> it = c.iterator();
		Vector<FileUpLoadServerThread> v = new Vector<>();
		
		while (it.hasNext()) {
			MultiChatServerThread t = server.clients.get(it.next());
			
			if( t == serverThread) continue;
			
			staticPort += 5;
			String msg = ip + "," + staticPort;
			SocketData sd = new SocketData("fileserverconnect", "server", oriFileName,msg);
			t.send.writeObject(sd);
			t.send.flush();
			
			FileUpLoadServerThread fut = new FileUpLoadServerThread(staticPort, folder,oriFileName);
			v.add(fut);
			fut.start();
			fut.join();
			
		}
		
		v.removeAllElements();
	}
	
	
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("서버시작");
			btnNewButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					Thread t = new Thread(FileDownloadServer.this);
					t.start();
				
				}
			});
			btnNewButton.setBounds(12, 10, 97, 31);
		}
		return btnNewButton;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(12, 58, 410, 140);
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}
	private JTextArea getResult() {
		if (result == null) {
			result = new JTextArea();
		}
		return result;
	}
}
